<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f2f5;
            height: 100vh;
            display: flex;
        }
        .sidebar {
            width: 250px;
            background: #2F2F2F;
            display: flex;
            flex-direction: column;
            border-right: 1px solid #242424;
        }
        .sidebar-header {
            padding: 18px;
            background: #2F2F2F;
            color: white;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #242424;
            height: 75px;
        }
        .user-info {
            display: flex;
            align-items: center;
            flex: 1;
            gap: 12px;
        }
        .avatar-upload {
            position: relative;
            cursor: pointer;
        }
        #userName {
            font-size: 16px;
            color: #fff;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 140px;
        }
        .avatar-upload:hover::after {
            content: '更换头像';
            position: absolute;
            bottom: -25px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            z-index: 1;
        }
        .search-box {
            padding: 10px 12px;
            background: #2F2F2F;
            border-bottom: 1px solid #242424;
        }
        .search-box input {
            width: 100%;
            padding: 8px 12px 8px 30px;
            border: none;
            border-radius: 4px;
            background: #1F1F1F url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="%23808080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>') 8px center no-repeat;
            color: white;
            outline: none;
            font-size: 13px;
        }
        .search-box input::placeholder {
            color: #808080;
        }
        .friend-list {
            flex: 1;
            overflow-y: auto;
            background: #2F2F2F;
        }
        .friend-item {
            padding: 12px;
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: background-color 0.2s;
            position: relative;
        }
        .friend-item:hover {
            background: #3F3F3F;
        }
        .friend-item.active {
            background: #3F3F3F;
        }
        .friend-info {
            display: flex;
            flex-direction: column;
            margin-left: 12px;
            flex: 1;
            min-width: 0;
        }
        .friend-name {
            color: white;
            font-size: 14px;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .friend-status {
            display: flex;
            align-items: center;
        }
        .status {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 6px;
        }
        .status.online {
            background: #95EC69;
        }
        .status.offline {
            background: #808080;
        }
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #F5F5F5;
        }
        .chat-header {
            padding: 12px 20px;
            background: #F5F5F5;
            border-bottom: 1px solid #E6E6E6;
        }
        .chat-header h2 {
            margin: 0;
            font-size: 16px;
            color: #000;
        }
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px 0;
            background: #F5F5F5;
        }
        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
            padding: 0 20px;
        }
        .message.sent {
            flex-direction: row-reverse;
        }
        .message-wrapper {
            display: flex;
            flex-direction: column;
            max-width: 60%;
        }
        .sent .message-wrapper {
            align-items: flex-end;
        }
        .received .message-wrapper {
            align-items: flex-start;
        }
        .message-content {
            padding: 10px 15px;
            border-radius: 3px 15px 15px 15px;
            margin: 0 15px;
            word-break: break-word;
            position: relative;
        }
        .sent .message-content {
            background: #95EC69;
            color: black;
            border-radius: 15px 3px 15px 15px;
        }
        .received .message-content {
            background: white;
            color: black;
        }
        .message-meta {
            font-size: 12px;
            color: #999;
            margin: 5px 15px;
        }
        .chat-input {
            padding: 0;
            border-top: 1px solid #E6E6E6;
            display: flex;
            flex-direction: column;
            background: #fff;
        }
        .chat-toolbar {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            gap: 8px;
            border-bottom: 1px solid #F1F1F1;
        }
        .tool-button {
            padding: 6px;
            background: none;
            border: none;
            cursor: pointer;
            color: #666;
            border-radius: 3px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }
        .tool-button:hover {
            background: #F1F1F1;
            color: #1890ff;
        }
        .input-area {
            display: flex;
            padding: 8px 12px;
            align-items: flex-end;
            min-height: 80px;
        }
        .message-input {
            flex: 1;
            border: none;
            outline: none;
            padding: 8px 0;
            margin-right: 12px;
            font-size: 14px;
            line-height: 1.5;
            resize: none;
            max-height: 120px;
            overflow-y: auto;
        }
        .send-button {
            padding: 6px 20px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            height: 32px;
        }
        .send-button:hover {
            background: #40a9ff;
        }
        .emoji-panel {
            position: absolute;
            bottom: 100%;
            left: 12px;
            background: white;
            border: 1px solid #E6E6E6;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 12px;
            display: none;
            width: 360px;
            height: 300px;
            overflow-y: auto;
            z-index: 1000;
        }
        .emoji-tabs {
            display: flex;
            border-bottom: 1px solid #E6E6E6;
            margin-bottom: 12px;
            position: sticky;
            top: 0;
            background: white;
            padding: 0 0 8px 0;
            gap: 12px;
        }
        .emoji-tab {
            padding: 4px 12px;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
            color: #666;
        }
        .emoji-tab:hover,
        .emoji-tab.active {
            background: #F1F1F1;
            color: #1890ff;
        }
        .emoji-grid {
            display: grid;
            grid-template-columns: repeat(8, 1fr);
            gap: 8px;
        }
        .emoji-item {
            font-size: 24px;
            padding: 8px;
            cursor: pointer;
            text-align: center;
            border-radius: 4px;
            transition: background-color 0.2s;
        }
        .emoji-item:hover {
            background: #F1F1F1;
        }
        .file-input {
            display: none;
        }
        .add-friend {
            margin-left: 10px;
            padding: 5px 10px;
            background: white;
            color: #1890ff;
            border: 1px solid #1890ff;
            border-radius: 4px;
            cursor: pointer;
        }
        .add-friend:hover {
            background: #e6f7ff;
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
        }
        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 400px;
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .modal-close {
            cursor: pointer;
            font-size: 20px;
        }
        .search-results {
            max-height: 300px;
            overflow-y: auto;
        }
        .user-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .user-item button {
            padding: 5px 10px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .friend-requests {
            position: fixed;
            bottom: 60px;
            left: 10px;
            width: 230px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            z-index: 1000;
            display: none;
        }
        .friend-requests.show {
            display: block;
        }
        .friend-requests-header {
            padding: 15px;
            background: #1890ff;
            color: white;
            border-radius: 8px 8px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .friend-requests-list {
            max-height: 300px;
            overflow-y: auto;
            padding: 10px;
        }
        .friend-request-item {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }
        .friend-request-item:last-child {
            border-bottom: none;
        }
        .friend-request-actions {
            display: flex;
            gap: 10px;
            margin-top: 8px;
        }
        .friend-request-actions button {
            flex: 1;
            padding: 5px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .accept-btn {
            background: #52c41a;
            color: white;
        }
        .reject-btn {
            background: #ff4d4f;
            color: white;
        }
        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ff4d4f;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }
        .emoji-button {
            padding: 10px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 20px;
            color: #666;
        }
        .emoji-button:hover {
            color: #1890ff;
        }
        .message-image {
            max-width: 200px;
            max-height: 200px;
            border-radius: 3px;
            cursor: pointer;
        }
        .message-file {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 5px;
            background: transparent;
        }
        .message-file i {
            font-size: 24px;
            color: #1890ff;
        }
        .message-file-info {
            display: flex;
            flex-direction: column;
        }
        .message-file-name {
            font-weight: bold;
        }
        .message-file-size {
            font-size: 12px;
            color: #666;
        }
        .image-preview {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 2000;
        }
        .image-preview.show {
            display: flex;
        }
        .image-preview img {
            max-width: 90%;
            max-height: 90%;
        }
        .image-preview-close {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 30px;
            cursor: pointer;
        }
        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 3px;
            object-fit: cover;
        }
        .message-content::before {
            content: '';
            position: absolute;
            top: 0;
            width: 0;
            height: 0;
            border: 6px solid transparent;
        }
        .sent .message-content::before {
            right: 100%;
            border-right-color: #95EC69;
        }
        .received .message-content::before {
            left: 100%;
            border-left-color: white;
        }
        .sidebar-footer {
            padding: 10px;
            border-top: 1px solid #242424;
            display: flex;
            gap: 10px;
        }
        .sidebar-footer button {
            flex: 1;
            padding: 8px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .sidebar-footer button:hover {
            background: #40a9ff;
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header">
            <div class="user-info">
                <div class="avatar-upload">
                    <img src="/uploads/avatars/default.png" alt="头像" class="user-avatar" id="userAvatar">
                    <input type="file" id="avatarInput" style="display: none" accept="image/*">
                </div>
                <span id="userName">加载中...</span>
            </div>
        </div>
        <div class="search-box">
            <input type="text" id="friendSearch" placeholder="搜索好友...">
        </div>
        <div class="friend-list" id="friendList"></div>
        <div class="sidebar-footer">
            <button onclick="showAddFriendModal()">添加好友</button>
            <button onclick="toggleFriendRequests()">好友请求<span id="requestBadge" class="notification-badge" style="display: none;">0</span></button>
        </div>
    </div>
    
    <div class="chat-container">
        <div class="chat-header">
            <h2 id="currentChat">请选择好友开始聊天</h2>
        </div>
        <div class="chat-messages" id="messageContainer"></div>
        <div class="chat-input">
            <div class="chat-toolbar">
                <button class="tool-button" onclick="toggleEmojiPanel()" title="表情">😊</button>
                <button class="tool-button" title="图片">
                    <span style="font-size: 18px;">📷</span>
                    <input type="file" class="file-input" accept="image/*" onchange="handleImageUpload(event)">
                </button>
                <button class="tool-button" title="文件">
                    <span style="font-size: 18px;">📎</span>
                    <input type="file" class="file-input" onchange="handleFileUpload(event)">
                </button>
            </div>
            <div class="input-area">
                <textarea 
                    class="message-input" 
                    id="messageInput" 
                    placeholder="输入消息..." 
                    rows="1"
                    onInput="this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px';"
                ></textarea>
                <button class="send-button" onclick="sendMessage()">发送</button>
            </div>
            <div class="emoji-panel" id="emojiPanel">
                <div class="emoji-tabs">
                    <div class="emoji-tab active" onclick="switchEmojiTab('faces')">表情</div>
                    <div class="emoji-tab" onclick="switchEmojiTab('gestures')">手势</div>
                    <div class="emoji-tab" onclick="switchEmojiTab('hearts')">心形</div>
                </div>
                <div class="emoji-grid" id="emojiGrid"></div>
            </div>
        </div>
    </div>

    <div class="friend-requests" id="friendRequests">
        <div class="friend-requests-header">
            <h3>好友请求</h3>
            <span class="modal-close" onclick="toggleFriendRequests()">&times;</span>
        </div>
        <div class="friend-requests-list" id="friendRequestsList"></div>
    </div>

    <div class="modal" id="addFriendModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加好友</h3>
                <span class="modal-close" onclick="hideAddFriendModal()">&times;</span>
            </div>
            <div class="search-box">
                <input type="text" id="userSearch" placeholder="搜索用户..." onkeyup="searchUsers()">
            </div>
            <div class="search-results" id="searchResults"></div>
        </div>
    </div>

    <div class="image-preview" id="imagePreview" onclick="closeImagePreview()">
        <span class="image-preview-close">&times;</span>
        <img src="" alt="预览图片">
    </div>

    <script>
        // 全局变量声明
        let ws;
        let currentFriend = null;
        let currentFriendInfo = null;
        const messageContainer = document.getElementById('messageContainer');
        const messageInput = document.getElementById('messageInput');
        const friendList = document.getElementById('friendList');
        const currentChat = document.getElementById('currentChat');
        const token = localStorage.getItem('token');

        if (!token) {
            window.location.href = '/';
        }

        // 连接WebSocket
        function connect() {
            ws = new WebSocket(`ws://${window.location.host}`);

            ws.onopen = () => {
                // 发送认证信息
                ws.send(JSON.stringify({
                    type: 'auth',
                    token: token
                }));
            };

            ws.onmessage = (event) => {
                const message = JSON.parse(event.data);
                handleMessage(message);
            };

            ws.onclose = () => {
                setTimeout(connect, 1000); // 断线重连
            };
        }

        connect();

        function handleMessage(message) {
            switch (message.type) {
                case 'friendList':
                    updateFriendList(message.friends);
                    break;
                case 'message':
                    displayMessage(message);
                    break;
                case 'userStatus':
                    updateUserStatus(message.userId, message.online);
                    break;
                case 'avatarUpdate':
                    updateUserAvatar(message.userId, message.avatar);
                    break;
                case 'error':
                    console.error(message.message);
                    break;
            }
        }

        // 添加好友搜索功能
        let allFriends = []; // 存储所有好友

        function updateFriendList(friends) {
            allFriends = friends; // 保存完整的好友列表
            displayFilteredFriends(friends); // 显示好友列表
        }

        function displayFilteredFriends(friends) {
            friendList.innerHTML = '';
            friends.forEach(friend => {
                const div = document.createElement('div');
                div.className = `friend-item${currentFriend === friend.id ? ' active' : ''}`;
                div.setAttribute('data-friend-id', friend.id);
                div.innerHTML = `
                    <img src="${friend.avatar || '/uploads/avatars/default.png'}" alt="头像" class="user-avatar">
                    <div class="friend-info">
                        <span class="friend-name">${friend.account}</span>
                        <div class="friend-status">
                            <span class="status ${friend.online ? 'online' : 'offline'}"></span>
                            <span style="color: #808080; font-size: 12px;">${friend.online ? '在线' : '离线'}</span>
                        </div>
                    </div>
                `;
                div.onclick = () => selectFriend(friend);
                friendList.appendChild(div);
            });
        }

        // 添加搜索事件监听
        document.getElementById('friendSearch').addEventListener('input', (e) => {
            const searchTerm = e.target.value.toLowerCase().trim();
            if (!searchTerm) {
                displayFilteredFriends(allFriends);
                return;
            }

            const filteredFriends = allFriends.filter(friend => 
                friend.account.toLowerCase().includes(searchTerm)
            );
            displayFilteredFriends(filteredFriends);
        });

        async function selectFriend(friend) {
            currentFriend = friend.id;
            currentFriendInfo = friend;
            currentChat.textContent = `正在与 ${friend.account} 聊天`;
            document.querySelectorAll('.friend-item').forEach(item => {
                item.classList.toggle('active', item.getAttribute('data-friend-id') === String(friend.id));
            });
            messageContainer.innerHTML = '';
            await loadMessages(friend.id);
        }

        async function loadMessages(friendId) {
            try {
                const response = await fetch(`/api/messages/${friendId}`, {
                    headers: {
                        'x-auth-token': token
                    }
                });
                const messages = await response.json();
                
                // 清空消息容器
                messageContainer.innerHTML = '';
                
                // 按时间顺序显示消息
                messages.forEach(message => {
                    displayMessage({
                        type: 'message',
                        id: message.id,
                        from: message.sender,
                        content: message.content,
                        timestamp: message.createdAt
                    });
                });
                
                messageContainer.scrollTop = messageContainer.scrollHeight;
            } catch (err) {
                console.error('加载消息失败:', err);
            }
        }

        function sendMessage() {
            const content = messageInput.value.trim();
            if (!content || !currentFriend) return;

            ws.send(JSON.stringify({
                type: 'message',
                to: currentFriend,
                content: content
            }));

            messageInput.value = '';
        }

        function displayMessage(message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${message.from.id === currentFriend ? 'received' : 'sent'}`;
            messageDiv.setAttribute('data-user-id', message.from.id);
            
            const avatar = document.createElement('img');
            avatar.src = message.from.avatar || '/uploads/avatars/default.png';
            avatar.className = 'user-avatar';
            avatar.alt = '头像';
            
            const wrapper = document.createElement('div');
            wrapper.className = 'message-wrapper';
            
            const content = document.createElement('div');
            content.className = 'message-content';

            // 解析消息内容
            let messageContent;
            try {
                messageContent = typeof message.content === 'string' && message.content.startsWith('{') 
                    ? JSON.parse(message.content) 
                    : { type: 'text', content: message.content };
            } catch (e) {
                messageContent = { type: 'text', content: message.content };
            }

            // 根据消息类型显示不同的内容
            if (message.contentType === 'image' || messageContent.type === 'image') {
                const img = document.createElement('img');
                img.src = messageContent.content;
                img.className = 'message-image';
                img.onclick = () => showImagePreview(messageContent.content);
                content.appendChild(img);
            } else if (message.contentType === 'file' || messageContent.type === 'file') {
                const fileDiv = document.createElement('div');
                fileDiv.className = 'message-file';
                const filename = messageContent.filename ? decodeURIComponent(messageContent.filename) : '未知文件';
                fileDiv.innerHTML = `
                    <i>📎</i>
                    <div class="message-file-info">
                        <span class="message-file-name">${filename}</span>
                        <a href="${messageContent.content}" target="_blank">下载文件</a>
                    </div>
                `;
                content.appendChild(fileDiv);
            } else {
                content.textContent = messageContent.content;
            }
            
            const meta = document.createElement('div');
            meta.className = 'message-meta';
            meta.textContent = new Date(message.timestamp).toLocaleTimeString();
            
            wrapper.appendChild(content);
            wrapper.appendChild(meta);
            
            messageDiv.appendChild(avatar);
            messageDiv.appendChild(wrapper);
            
            messageContainer.appendChild(messageDiv);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }

        function updateUserStatus(userId, online) {
            const friendItem = document.querySelector(`.friend-item[data-friend-id="${userId}"] .status`);
            if (friendItem) {
                friendItem.className = `status ${online ? 'online' : 'offline'}`;
            }
        }

        function updateUserAvatar(userId, avatarUrl) {
            // 更新好友列表中的头像
            const friendItem = document.querySelector(`.friend-item[data-friend-id="${userId}"] img`);
            if (friendItem) {
                friendItem.src = avatarUrl;
            }

            // 更新聊天消息中的头像
            const messageAvatars = document.querySelectorAll(`.message[data-user-id="${userId}"] .user-avatar`);
            messageAvatars.forEach(avatar => {
                avatar.src = avatarUrl;
            });

            // 更新当前好友信息缓存
            if (currentFriendInfo && currentFriendInfo.id === userId) {
                currentFriendInfo.avatar = avatarUrl;
            }
        }

        function showAddFriendModal() {
            document.getElementById('addFriendModal').style.display = 'flex';
        }

        function hideAddFriendModal() {
            document.getElementById('addFriendModal').style.display = 'none';
        }

        async function searchUsers() {
            const searchTerm = document.getElementById('userSearch').value.trim();
            if (searchTerm.length < 2) return;

            try {
                const response = await fetch(`/api/friends/search/${searchTerm}`, {
                    headers: {
                        'x-auth-token': token
                    }
                });
                const users = await response.json();
                displaySearchResults(users);
            } catch (err) {
                console.error('搜索用户失败:', err);
            }
        }

        function displaySearchResults(users) {
            const resultsContainer = document.getElementById('searchResults');
            resultsContainer.innerHTML = '';
            
            users.forEach(user => {
                const div = document.createElement('div');
                div.className = 'user-item';
                div.innerHTML = `
                    <span>${user.account}</span>
                    <button onclick="sendFriendRequest('${user.id}')">添加好友</button>
                `;
                resultsContainer.appendChild(div);
            });
        }

        async function sendFriendRequest(userId) {
            try {
                const response = await fetch(`/api/friends/request/${userId}`, {
                    method: 'POST',
                    headers: {
                        'x-auth-token': token
                    }
                });
                const data = await response.json();
                alert(data.msg);
                hideAddFriendModal();
            } catch (err) {
                console.error('发送好友请求失败:', err);
            }
        }

        // 按回车发送消息
        messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 定期检查好友请求
        async function checkFriendRequests() {
            try {
                const response = await fetch('/api/friends/requests', {
                    headers: {
                        'x-auth-token': token
                    }
                });
                const requests = await response.json();
                updateFriendRequests(requests);
            } catch (err) {
                console.error('检查好友请求失败:', err);
            }
        }

        function updateFriendRequests(requests) {
            const requestsList = document.getElementById('friendRequestsList');
            const requestBadge = document.getElementById('requestBadge');
            
            if (requests.length > 0) {
                requestBadge.style.display = 'flex';
                requestBadge.textContent = requests.length;
            } else {
                requestBadge.style.display = 'none';
            }

            requestsList.innerHTML = '';
            requests.forEach(request => {
                const div = document.createElement('div');
                div.className = 'friend-request-item';
                div.innerHTML = `
                    <div>来自 ${request.sender.account} 的好友请求</div>
                    <div class="friend-request-actions">
                        <button class="accept-btn" onclick="handleFriendRequest('${request.id}', 'accept')">接受</button>
                        <button class="reject-btn" onclick="handleFriendRequest('${request.id}', 'reject')">拒绝</button>
                    </div>
                `;
                requestsList.appendChild(div);
            });
        }

        function toggleFriendRequests() {
            const requestsPanel = document.getElementById('friendRequests');
            requestsPanel.classList.toggle('show');
        }

        async function handleFriendRequest(requestId, action) {
            try {
                const response = await fetch(`/api/friends/request/${requestId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'x-auth-token': token
                    },
                    body: JSON.stringify({ action })
                });
                const data = await response.json();
                alert(data.msg);
                
                if (action === 'accept') {
                    // 重新连接WebSocket以刷新好友列表
                    ws.close();
                    setTimeout(connect, 1000);
                }
                
                checkFriendRequests(); // 刷新好友请求列表
            } catch (err) {
                console.error('处理好友请求失败:', err);
            }
        }

        // 页面加载时立即检查好友请求
        checkFriendRequests();
        setInterval(checkFriendRequests, 30000); // 每30秒检查一次

        // 表情数据
        const emojiData = {
            faces: [
                '😀', '😃', '😄', '😁', '😅', '😂', '🤣', '😊',
                '😇', '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘',
                '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪',
                '🤨', '🧐', '🤓', '😎', '🤩', '🥳', '😏', '😒'
            ],
            gestures: [
                '👋', '🤚', '🖐️', '✋', '🖖', '👌', '🤌', '🤏',
                '✌️', '🤞', '🤟', '🤘', '🤙', '👈', '👉', '👆',
                '🖕', '👇', '☝️', '👍', '👎', '✊', '👊', '🤛',
                '🤜', '👏', '🙌', '👐', '🤲', '🤝', '🙏', '✍️'
            ],
            hearts: [
                '❤️', '🧡', '💛', '💚', '💙', '💜', '🤎', '🖤',
                '🤍', '💔', '❤️‍🔥', '❤️‍🩹', '💖', '💗', '💓', '💞',
                '💕', '💝', '💘', '💌', '💟', '💑', '💏', '👩‍❤️‍👨',
                '👨‍❤️‍👨', '👩‍❤️‍👩', '💋', '💯', '💢', '💥', '💫', '💦'
            ]
        };

        let currentEmojiTab = 'faces';

        function toggleEmojiPanel() {
            const panel = document.getElementById('emojiPanel');
            panel.classList.toggle('show');
            if (panel.classList.contains('show')) {
                renderEmojis();
            }
        }

        function switchEmojiTab(tab) {
            currentEmojiTab = tab;
            document.querySelectorAll('.emoji-tab').forEach(t => {
                t.classList.toggle('active', t.textContent === {
                    'faces': '表情',
                    'gestures': '手势',
                    'hearts': '心形'
                }[tab]);
            });
            renderEmojis();
        }

        function renderEmojis() {
            const grid = document.getElementById('emojiGrid');
            grid.innerHTML = '';
            emojiData[currentEmojiTab].forEach(emoji => {
                const div = document.createElement('div');
                div.className = 'emoji-item';
                div.textContent = emoji;
                div.onclick = () => insertEmoji(emoji);
                grid.appendChild(div);
            });
        }

        function insertEmoji(emoji) {
            const input = document.getElementById('messageInput');
            const start = input.selectionStart;
            const end = input.selectionEnd;
            const text = input.value;
            input.value = text.substring(0, start) + emoji + text.substring(end);
            input.selectionStart = input.selectionEnd = start + emoji.length;
            input.focus();
        }

        // 点击其他地方关闭表情面板
        document.addEventListener('click', (e) => {
            const panel = document.getElementById('emojiPanel');
            const button = document.querySelector('.emoji-button');
            if (!panel.contains(e.target) && !button.contains(e.target)) {
                panel.classList.remove('show');
            }
        });

        async function handleImageUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件');
                return;
            }

            await uploadAndSendFile(file, 'image');
            event.target.value = ''; // 清空input以允许上传相同文件
        }

        async function handleFileUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            await uploadAndSendFile(file, 'file');
            event.target.value = ''; // 清空input以允许上传相同文件
        }

        async function uploadAndSendFile(file, type) {
            try {
                const formData = new FormData();
                // 使用 Blob 来确保文件名编码正确
                const blob = new Blob([file], { type: file.type });
                formData.append('file', blob, encodeURIComponent(file.name));

                const response = await fetch('/api/upload', {
                    method: 'POST',
                    headers: {
                        'x-auth-token': token
                    },
                    body: formData
                });

                const data = await response.json();
                if (response.ok) {
                    ws.send(JSON.stringify({
                        type: 'message',
                        to: currentFriend,
                        contentType: type,
                        content: data.url,
                        filename: encodeURIComponent(file.name)
                    }));
                } else {
                    alert(data.msg || '文件上传失败');
                }
            } catch (err) {
                console.error('文件上传失败:', err);
                alert('文件上传失败');
            }
        }

        function showImagePreview(url) {
            const preview = document.getElementById('imagePreview');
            preview.querySelector('img').src = url;
            preview.classList.add('show');
        }

        function closeImagePreview() {
            const preview = document.getElementById('imagePreview');
            preview.classList.remove('show');
        }

        // 加载用户信息
        async function loadUserInfo() {
            try {
                const response = await fetch('/api/auth/me', {
                    headers: {
                        'x-auth-token': token
                    }
                });
                const user = await response.json();
                document.getElementById('userName').textContent = user.account;
                document.getElementById('userAvatar').src = user.avatar;
            } catch (err) {
                console.error('加载用户信息失败:', err);
            }
        }

        // 处理头像上传
        document.getElementById('userAvatar').addEventListener('click', () => {
            document.getElementById('avatarInput').click();
        });

        document.getElementById('avatarInput').addEventListener('change', async (event) => {
            const file = event.target.files[0];
            if (!file) return;

            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件');
                return;
            }

            const formData = new FormData();
            formData.append('avatar', file);

            try {
                const response = await fetch('/api/auth/avatar', {
                    method: 'POST',
                    headers: {
                        'x-auth-token': token
                    },
                    body: formData
                });

                const data = await response.json();
                if (response.ok) {
                    document.getElementById('userAvatar').src = data.avatar;
                } else {
                    alert(data.msg || '头像上传失败');
                }
            } catch (err) {
                console.error('头像上传失败:', err);
                alert('头像上传失败');
            }
        });

        // 页面加载完成后自动加载用户信息
        document.addEventListener('DOMContentLoaded', async () => {
            if (token) {
                await loadUserInfo();
                connect(); // 连接WebSocket
            } else {
                window.location.href = '/';
            }
        });

        // 修改文件上传按钮点击事件
        document.querySelectorAll('.tool-button').forEach(button => {
            const input = button.querySelector('.file-input');
            if (input) {
                button.addEventListener('click', () => input.click());
            }
        });

        // 自动调整输入框高度
        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html> 